<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\WeChat\WeChatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller
{
    /**
     * 登录
     */
    public function login(Request $request)
    {
        $type = $request->type;
        switch ($type){
            case 'mini':
                $validate = $request->validate([
                    'code' => 'bail|required|string',
                    'phoneCode' => 'bail|string',
                ]);
                return $this->handleMiniLogin($validate['code'], $validate['phoneCode'] ?? '');
            case 'password':
                //密码登录
                $validate = $request->validate([
                    'phone' => 'bail|required|string|regex:/^1[3-9]\d{9}$/',
                    'password' => 'bail|required|string|min:6'
                ],[
                    'phone.required' => '手机号为必填项',
                    'phone.string' => '手机号必须为字符串',
                    'phone.regex' => '请输入有效的11位手机号',
                    'password.required' => '密码为必填项',
                    'password.string' => '密码必须为字符串',
                    'password.min' => '密码长度不能少于6位',
                ]);
                return $this->handlePhoneLogin($validate,'password');
            case 'verifyCode':
                //验证码登录
                $validate = $request->validate([
                    'phone' => 'bail|required|string|regex:/^1[3-9]\d{9}$/',
                    'verifyCode' => 'bail|required|size:6',
                ],[
                    'phone.required' => '手机号为必填项',
                    'phone.string' => '手机号必须为字符串',
                    'phone.regex' => '请输入有效的11位手机号',
                    'verifyCode.required' => '验证码为必填项',
                    'verifyCode.size' => '验证码必须为6位数字',
                ]);
                return $this->handlePhoneLogin($validate,'verifyCode');
            case 'debug':
                $user = User::find(1);
                $token = $user->createToken('user_' . $user->id, ['*'], now()->addWeek());
                return apiResponse(0, '登录成功', ['token' => $token->plainTextToken]);
            default:
                return apiResponseError([4010, '缺少必要参数']);
        }

    }


    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return apiResponse(msg: '退出成功');
    }

    /**
     * 获取当前用户信息
     */
    public function me(Request $request)
    {
        return apiResponse(data: $request->user());
    }

    /**
     * 处理手机号登录
     */
    private function handlePhoneLogin($params = [],$type = 'password1')
    {
        $user = User::where('phone', $params['phone'])->first();
        if (!$user) {
            //测试先自动注册
//            if($type === 'verifyCode'){
//                $user = User::create([
//                    'phone' => $params['phone'],
//                    'password' => '123456',
//                    'nickname' => '用户_' . substr($params['phone'], -4), // 默认昵称（取手机号后4位）
//                ]);
//            }else{
//                return apiResponseError([4010, '账号不存在']);
//            }
            return apiResponseError([4010, '账号不存在']);
        }
        if($type === 'verifyCode'){
            if($params['verifyCode'] !== '623367'){
                return apiResponseError([4010, '验证码错误']);
            }
        }else if (! Hash::check($params['password'], $user->password)) {
            return apiResponseError([4010, '密码错误']);
        }
        // 生成token
        $token = $user->createToken('user_' . $user->id, ['*'], now()->addWeek());
        return apiResponse(0, '登录成功', [
            'token' => $token->plainTextToken,
            'userInfo' => $user
        ]);

    }
    /**
     * 小程序登录处理
     */
    private function handleMiniLogin($code, $phoneCode = '')
    {
        $weChatService = new WeChatService();
        $wxInfo = $weChatService->getWxInfoByCode($code);
        $user = User::query()->firstOrCreate(
            ['openid' => $wxInfo['openid']],
            [
                'nickname' => '微信用户',
                'register_ip' => request()->getClientIp()
            ]
        );
        // 绑定微信手机号
        if (!$user->phone && $phoneCode) {
            $phoneInfo = $weChatService->getWxPhoneInfo($phoneCode);
            if (User::where('phone', $phoneInfo['phoneNumber'])->exists()) {
                Log::info("用户（{$wxInfo['openid']}）的手机号{$phoneInfo['phoneNumber']}已被其他账号绑定");
                return apiResponseError([4011, '该手机号已被其他账号绑定']);
            }
            $user->update(['phone' => $phoneInfo['purePhoneNumber']]);
        }
        // 更新登录信息
        $user->update(['login_ip' => request()->getClientIp(), 'login_time' => now()]);
        // 生成token
        $token = $user->createToken('user_' . $user->id, ['*'], now()->addWeek());
        return apiResponse(0, '登录成功', [
            'token' => $token->plainTextToken,
            'userInfo' => $user
        ]);
    }
}
